<?php

namespace app\admin\model;

use think\Model;
use EasyWeChat\Foundation\Application;

class DormitoryDorm extends Model
{
    // 连接数据库名称
    //protected $connection = 'db2';
    // 表名
    protected $name = 'dormitory_dorm';
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'created_at';
    protected $updateTime = false;

    const NORMAL = 1;
    const HIDDEN = 0;

    /**
     * @var array 寝室类别
     */
    public static $categoryList = [
        '1' => '公寓',
        '2' => '单间',
    ];

    /**
     * @var array 寝室类型
     */
    public static $typeList = [
        '1' => '男寝室',
        '2' => '女寝室',
        '3' => '混合寝室',
    ];

    public static $genderTypeList = [
        '1' => '1',
        '2' => '2'
    ];

    public static $userTypeList = [
        '1' => '学生寝室',
        '2' => '办公室',
        '3' => '配电房',
        '4' => '值班室',
        '5' => '其他',
    ];

    public function creator()
    {
        return $this->belongsTo('Admin', 'creator_id', 'id', [], 'LEFT')->field('id,nickname');
    }

    /*public function garden()
    {
        return $this->belongsTo('DormitoryGarden', 'garden_number', 'number', [], 'LEFT')->field('id,name,number');
    }

    public function building()
    {
        return $this->belongsTo('DormitoryBuilding', 'building_number', 'number', [], 'LEFT')->field('id,name,number');
    }*/

    public function getTypeTextAttr($value, $data)
    {
        $status = static::$typeList;
        return $status[$data['type']];
    }

    public function getCategoryTextAttr($value, $data)
    {
        $status = static::$userTypeList;
        return $status[$data['category']];
    }

    public static function generateQrcode($dorm_id, $force = false, $is_hyaline = false)
    {
        $options = [
            'app_id'   => 'wxf358173ee84af7d4',
            'secret'   => '033ace5a5fa6de52a2d43d04ecf99976',
            'token'    => '',
            'aes_key'  => ''
        ];

        $app = new Application($options);
        $accessToken = $app->access_token;
        $token = $accessToken->getToken();

        $params = [
            'scene' => $dorm_id,
            'page'  => 'pages/scan-evaluation/index',
            'width' => 600,
            'auto_color' => false,
            'line_color' => ['r' => 0, 'g' => 0, 'b' => 0],
            'is_hyaline' => $is_hyaline,
        ];

        $code = self::getWXACodeUnlimit($token, $params);


        $public_path = ROOT_PATH . 'public';
        $uploads_path ='/uploads/' . date('Ymd', time()) . "/";

        if (!file_exists($public_path . $uploads_path)) {
            //检查是否有该文件夹，如果没有就创建，并给予最高权限
            mkdir($public_path . $uploads_path, 0777,true);
        }
        $filename = uniqid() . ".png";
        $new_file = $public_path . $uploads_path . $filename;

        $flag = file_put_contents($new_file, $code);

        if (!$flag) {
            return '';
        }

        $qrcode = $uploads_path . $filename;

        return $qrcode;

        /*$flag = DormitoryDorm::where('id', $dorm_id)->update(['qrcode' => $qrcode]);
        if ($flag) return $qrcode;
        return '';*/
    }

    public static function getWXACodeUnlimit($access_token = null, $params)
    {

        $url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=$access_token";

        //设置post数据
        $data_string = json_encode($params);

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json; charset=utf-8',
                'Content-Length: ' . strlen($data_string))
        );

        if(stripos($url,"https://")!==FALSE) {
            curl_setopt($ch, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        }else {
            curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,TRUE);
            curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,2);//严格校验
        }

        $result = curl_exec($ch);
        $err = curl_error($ch);

        if (false === $result || !empty($err)) {
            $errno = curl_errno($ch);
            $info = curl_getinfo($ch);
            curl_close($ch);

            return array(
                'status' => 250,
                'errno' => $errno,
                'msg' => $err,
                'data' => $info,
            );
        }

        curl_close($ch);

        return $result;
    }

}
